'''
Created on 19/11/2010

@author: inyaky
'''
from google.appengine.api import users
from google.appengine.ext import db
from model.uCategory import Category
from model.uTask import Task
from model.userConf import UserConf
import datetime
import uConst

class UserAdapter(object):
    
    def getCategoryList(self):
        if self._adaptedUser : 
            return db.GqlQuery('Select * from Category where _owner= :owner', owner=users.get_current_user())
    
    def getTaskList(self):
        list = []
        for aTask in Task.gql('where _owner=:owner and _parent=:parent', owner=self._adaptedUser, parent=self._positionToParentTask()):
            list = list + [aTask]
        for aTask in Task.gql('where _owner!=:owner and _sharedUsers=:ownerEmail and _parent=:parent', owner=self._adaptedUser, ownerEmail=self.getEmail(), parent=self._positionToParentTask()):
            list = list + [aTask]    
        return list
        
    def getTaskCount(self):
        return self.taskList.count()
    
    def createCategory(self,name):
        aCategory = Category()
        aCategory.setName(name)
        aCategory.setOwner(self._adaptedUser)
        return aCategory
    
    def createTask(self, name, category):
        aTask = Task()
        aTask.setOwner(self._adaptedUser)
        aTask.setName(name)
        aTask.setCateogry(category)
        aTask.setCreationDate(datetime.datetime.today())
        aTask.setUpdateDate(aTask.getCreationDate(),self._adaptedUser)
        aTask.setParent(self._positionToParentTask())
        aTask._completed = False
        return aTask
    
    def deleteTask(self,aTask):
        if aTask.getSubTasks!=None:
            for itTask in aTask.getSubTasks():
                self.deleteTask(itTask)
        db.delete(aTask)
        
    def deleteCategory(self,aCategory):
        db.delete(aCategory)
    
    def getTaskByName(self,name):
        for aTask in self.getTaskList():
            if aTask.getName()==name:
                resu=aTask
                break
        return resu
    
    def getCategoryByName(self,name):
        for aCategory in self.getCategoryList():
            if aCategory.getName()==name:
                resu=aCategory
                break
        return resu
    
    def getCategoryByKey(self,aKey):
        return db.get(aKey)
    
    def getTaskByKey(self,aKey):
        return db.get(aKey)
    
    def isLogged(self):
        return not self._adaptedUser is None
    
    def LogIn(self):
        self._enviroment.redirect('/welcome')
        
    def LogOut(self):
        self._enviroment.redirect(users.create_logout_url('/'))
        
    def getEmail(self):
        if self.isLogged():
            return self._adaptedUser.email()
        
    def _positionToParentTask(self):
        if self._position:
            return db.get(self._position)
        else:
            return None
            
    def _positionToRenderable(self,aTask):
        if aTask==None:
            return '/<a class="position_link" href="/">' + self.getEmail() + '</a>'
        else:
            return self._positionToRenderable(aTask.getParent()) + '/<a class="position_link" href="/?position='  + str(aTask.key()) + '">' + aTask.getName() + '</a>'
        
    def getAdaptedUser(self):
        return self._adaptedUser    
    
    def getConf(self):
        if ( UserConf.gql('where _owner=:owner',owner=self._adaptedUser).count()==0):
            conf = UserConf()
            conf.setOwner(self._adaptedUser)
            conf.setTheme('default.css')
        else:
            conf = UserConf.gql('where _owner=:owner',owner=self._adaptedUser)[0]
        return conf
    
    def toRenderable(self):
        return {'email':self.getEmail(), 'position':self._position, 'render_position':self._positionToRenderable(self._positionToParentTask()), 'theme':self.getConf().getTheme()}
    
    
    def __init__(self,aEnviroment):
        self._enviroment = aEnviroment 
        self._adaptedUser = users.get_current_user()
        self._position = self._enviroment.request.get('position')
        


   
        
